package org.transfer.service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.transfer.model.ImportLog;
import org.transfer.utils.ConfigUtil;
import org.transfer.utils.LogUtils;
import org.transfer.utils.PGPUtils;

@Component
public class DecryptFileService {

	@Autowired
	private ImportLogService importLogService;

	private String logPath = "";

	/**
	 * 解密方法
	 * 
	 * @throws IOException
	 */
	public void decryptFile() throws IOException {
		System.out.println("===================解密开始===================");
		String decryptPath = ConfigUtil.getConfigure().getProperty("decryptPath");
		String decryptOutPath = ConfigUtil.getConfigure().getProperty("decryptOutPath");
		String ascKeyFilePath = ConfigUtil.getConfigure().getProperty("ascKeyFilePath");
		String ascPassword = ConfigUtil.getConfigure().getProperty("ascPassword");
		String logsFile = ConfigUtil.getConfigure().getProperty("logsFile");
		File logFile = new File(logsFile);
		if (!logFile.exists()) {
			logFile.mkdirs();
		}
		logPath = logsFile + "decrypt.log";
		List<File> list = new ArrayList<File>();
		scanningFile(list, decryptPath);
		List<File> outlist = new ArrayList<File>();
		scanningFile(outlist, decryptOutPath);
		for (File inputFile : list) {
			// 判断文件是否合法
			// 只处理7z压缩加密文件
			String fileName = inputFile.getName().toUpperCase();
			if (!(fileName.indexOf(".") != -1 && (fileName.indexOf("7Z") != -1 || fileName.indexOf("GPG") != -1)
					&& ("7Z".equals(fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()))
							|| "GPG".equals(fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length())))
					&& fileName.indexOf("_") != -1 && fileName.split("_").length == 5)) {

				LogUtils.logs(logPath, "【" + fileName + "】文件格式不合法");
				continue;
			}
			// 需要解密状态
			boolean flag = true;
			// 判断如果输出文件夹有该文件则无需解密
			for (File outFile : outlist) {
				if (inputFile.getName().equals(outFile.getName())) {
					flag = false;
					break;
				}
			}
			if (!flag) {
				LogUtils.logs(logPath, "【" + inputFile.getName() + "】无需解密");
				continue;
			}
			ImportLog entity = importLogService
					.get(new ImportLog(inputFile.getName().substring(0, inputFile.getName().indexOf("."))));
			try {
				PGPUtils.declassifiedFile(inputFile.getPath(), decryptOutPath, ascKeyFilePath, ascPassword);
				LogUtils.logs(logPath, "【" + inputFile.getName() + "】解密成功");
				if (entity != null) {
					entity.setDecryptState("1");
					entity.setDecryptMsg("解密成功");
					importLogService.save(entity);
				}
			} catch (Exception e) {
				LogUtils.logs(logPath, "【" + inputFile.getName() + "】解密失败");
				if (entity != null) {
					entity.setDecryptState("0");
					entity.setDecryptMsg("解密失败，系统内部错误！");
					importLogService.save(entity);
				}
			}
		}
		System.out.println("===================解密结束===================");
	}

	/**
	 * 获取加密文件集合
	 * 
	 * @param list
	 * @param filePath
	 * @return
	 */
	public List<File> scanningFile(List<File> list, String filePath) {
		File document = new File(filePath);
		if (!document.exists()) {
			document.mkdirs();
		}
		if (!document.isFile()) {
			File[] files = document.listFiles();
			for (File file : files) {
				scanningFile(list, file.getPath());
			}
		} else {
			list.add(document);
		}
		return list;
	}

}
